use std::{fs::File, io::Read};
use lazy_static::lazy_static;
use serde::Deserialize;

// use rocket::{catch, catcher, delete, get, put, post, routes, catchers, build};
use serde_json::{json, Value};
use std::fs;
use sqlx;
use std::env;
use sqlx::postgres::PgRow;
use sqlx::{postgres::PgPoolOptions, Executor, postgres::PgPool,Row};
use sqlx::FromRow;
use crate::tools::settings::{Setting};


pub fn read_toml() -> Setting {
    let setting = Setting::default();
    // println!("{:#?}",setting);
    // Setting::get();
    // let c = Setting::get();
    // println!("返回整个配置:{:#?}", c);
    // println!("调用的字段:{:#?}", setting.database.admin_passwd);
    Setting {
        database: setting.database,
        options: setting.options,
    }
}



/// pgsql连接
pub async fn pgsql_conn() -> sqlx::Result<PgPool> {
    // 根据实际数据库配置修改
    let c = read_toml();
    let db_name = c.database.db_name;
    let db_host = c.database.db_host;
    let db_port = c.database.db_port;
    let db_user = c.database.db_user;
    let db_password = c.database.db_password;
    let max_connections = c.database.max_connections;

    let conn_str =&format!(
        "postgres://{}{}{}@{}{}{}{}{}",
        db_user,
        if db_password.is_empty(){""}else{":"},
        db_password,
        db_host,
        if db_port.is_empty(){""}else{":"},
        db_port,
        if db_name.is_empty(){""}else{"/"},
        db_name
    );

    println!("数据库URL: {}", conn_str);

    // let str ="postgres://odoo:123456@localhost:5432/odoo17";
    PgPoolOptions::new().after_connect(|conn, _meta| Box::pin(async move {
        conn.execute("SET TIME ZONE 'Asia/Shanghai';").await?;
        Ok(())
    })).max_connections(max_connections).connect(conn_str).await
}



/// pgsql的sql执行
/// @param database_conn 数据库连接
/// @param sql 执行的sql
pub async fn execute(database_conn: sqlx::PgPool, sql: &str) -> Vec<sqlx::postgres::PgRow> {
    return sqlx::query(&sql)
        .fetch_all(&database_conn)
        .await.unwrap();
}